<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ActiveAddFriendConfigMapper;
use App\CustHub\Mapper\ChRobotMapper;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\Transaction;
use function Hyperf\Collection\collect;

class ActiveAddFriendConfigService extends AbstractService
{
    public $mapper;

    #[Inject]
    protected ChConfigService $configService;

    #[Inject]
    protected ChRobotMapper $robotMapper;

    #[Inject]
    protected Redis $redis;

    protected string $cachePrefix = 'ch_add_friend_operate_config';
    public function __construct(ActiveAddFriendConfigMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function getConfig($params,$groupKey = 'active_add_friend'): array
    {
        $uid = $params['uid'];
        $mainUid = $params['main_uid'];
        $config = $this->configService->getConfigByGroupKey($uid,$mainUid,$groupKey);
        return collect($config)->map(function ($item) {
            $value = json_decode($item['value'], true);
            // 检查 json_decode 是否成功，如果失败则使用原始值
            if (json_last_error() === JSON_ERROR_NONE) {
                $item['value'] = $value;
            }

            return [
                'id' => $item['id'],
                'key' => $item['key'],
                'value' => $item['value']
            ];
        })->values()->toArray();
    }

    public function getOperateConfig($params)
    {
        $uid = $params['uid'];
        $cacheName = $this->cachePrefix.md5((string)$uid);

        $list = $this->redis->get($cacheName);
        if(!empty($list)){
            return $list;
        }

        $config = $this->mapper->model::query()
            ->select(['uid','is_auto_node', 'is_update_node', 'node_content','is_auto_operate','operate_cfg',
                ])
            ->where('uid',$uid)
            ->first();
        $this->redis->set($cacheName,$config,3600);
        return $config;
    }

    #[Transaction]
    public function saveConfig(array $params): bool
    {
        $group = "active_add_friend";
        $params['group'] = $group;
        $this->configService->saveConfig($params);
        return true;
    }

    public function saveOperateConfig($uid, $params): bool
    {
        $fieldsToConvert = ['node_content', 'operate_cfg'];

        foreach ($fieldsToConvert as $field) {
            if (isset($params[$field]) && is_string($params[$field])) {
                $params[$field] = json_decode($params[$field], true);
            }
        }

        // 处理operate_cfg中的robot_id替换
        if (!empty($params['operate_cfg']['draw_group_cfg'])) {
            $robotIds = [];

            // 收集所有robot_id
            foreach ($params['operate_cfg']['draw_group_cfg'] as &$drawCfg) {
                foreach ($drawCfg['rooms'] as &$room) {
                    $robotIds[] = $room['robot_id'];
                }
            }

            // 批量查询robot信息
            $robots = $this->robotMapper->findByIds(array_unique($robotIds),'id,user_id');
            $robotMap = collect($robots)->keyBy('id')->map(function ($item) {
                return $item['user_id'];
            })->toArray();

            // 替换robot_id为user_id
            foreach ($params['operate_cfg']['draw_group_cfg'] as &$drawCfg) {
                foreach ($drawCfg['rooms'] as &$room) {
                    if (isset($robotMap[$room['robot_id']])) {
                        $room['create_user_id'] = $robotMap[$room['robot_id']];
                        unset($room['robot_id']); // 移除原robot_id字段
                    }
                }
            }
        }

        $check = $this->mapper->checkUid($uid);
        if (!$check) {
            $this->mapper->model::insert($params);
        }

        $config = $this->mapper->model::query()->find($uid);
        if ($config) {
            $fillFields = $config->getFillable();
            $validParams = array_intersect_key($params, array_flip($fillFields));
            $config->update($validParams);
        }

        $cacheName = $this->cachePrefix.md5((string)$uid);
        $this->redis->del([$cacheName]);

        return true;
    }

    public function getConfigValue(array $config, string $key, bool $isTime = false)
    {
        foreach ($config as $item) {
            if ($item['key'] === $key) {
                return $item['value'];
            }
        }
        return null;
    }
}